package cn.ffcs.bpmpvc.web;

import java.io.File;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.echoice.paper.PageBean;
import org.echoice.paper.PageNavi;
import org.echoice.util.DateUtil;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.TransactProcessStatus;
import cn.ffcs.bpmpvc.model.AppSms;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.services.AppSmsService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.web.forms.FlowTaskForm;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.organ.model.Organization;
import cn.ffcs.organ.model.Person;
import cn.ffcs.security.model.User;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.util.context.ApplicationContextUtil;
/**
 * 短信、彩信申请流程
 * @author wujy
 *
 */
@SuppressWarnings("serial")
public class FlowSmsAction extends FlowAppBaseAction<TransactProcessStatus>{
	private AppBusinessReqService appBusinessReqService;
	private AppSmsService appSmsService;
	private FlowTaskForm flowTaskForm;
	private AppSms appSms;
	private String procinstId;
	
	/** 附件上传 * */
	private List<File> uploads;
	private List<String> filetype;
	/** 要删除的文件* */
	private List<String> delDocumentIds;
	
	public String findList(){
		HttpServletRequest request=ApplicationContextUtil.getHttpServletRequest();
		if(flowTaskForm==null){
    		flowTaskForm=new FlowTaskForm();
    	}
		User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
		flowTaskForm.setUserId(user.getPerson().getId().toString());
		PageBean  pageBean=appSmsService.getAppSmsDao().queryPageSmsList(flowTaskForm, PageNavUtil.getPageNo(request), PageNavUtil.getPageSize(request));
		request.setAttribute("appSmslist", pageBean.getDataList());
        String pageNaviStr=PageNavi.getPageNaviText(request, pageBean);
        request.setAttribute("pageNaviStr", pageNaviStr);
		return "toSmsList";
	}
	
	public String applyInit(){
		User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
		Organization startDept=getAppBusinessReqService().getOrgByPerson(user.getPerson());
		String processId=getAppBusinessReqService().getAppSmsProcessId();
		ProcessView processView=appSmsService.getProcessPvcService().getInitProcessInfo(processId,null,startDept);
		//得到产品经理角色用户
        List<Person> prodList=appBusinessReqService.findProdListByRole();
        ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("processView", processView);
        appSms=new AppSms();
        appSms.setApplyUser(user.getPerson().getId().toString());
        appSms.setApplyUserName(user.getPerson().getName());
        appSms.setApplyDept(startDept.getId().toString());
        appSms.setApplyDeptName(startDept.getFullName());
        appSms.setOpTime(new Date());
        appSms.setSercodeTextRate(4L);
        appSms.setSercodeMultRate(4L);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("appSms", appSms);
        String reqImportType = "REQ_IMPORT_TYPE";
       
        List<Dict> importances=getAppBusinessReqService().getAppBusinessReqDao().findDict(reqImportType);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("importances", importances);
        String userId=ApplicationContextUtil.getUserContextObject().getCurrUser().getPersonID();
		if(userId.equalsIgnoreCase(appSms.getApplyUser())){
			ApplicationContextUtil.getHttpServletRequest().setAttribute("showEndBtn", "true");
		}
		return "toSmsApply";
	}

	public String saveStartFlow(){
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);
        User user =ApplicationContextUtil.getUserContextObject().getCurrUser();
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String processId=req.getParameter("processId");
        Person prodPerson=new Person();
        prodPerson.setId(Integer.valueOf(appSms.getProdUser()));
        Organization prodDept=appBusinessReqService.getOrgByPerson(prodPerson);
        if(prodDept!=null){
        	appSms.setProdDept(prodDept.getId().toString());
        }
        
        if(isCommit){
            returnMsg="业务需求单提交成功";
        }else{
            returnMsg="业务需求单记录保存成功";
        }
        try{
        	setAllDateField(appSms);
			ProcTranRecord procTranRecord=getAppSmsService().saveAndStartFlow(processId, user.getPerson(), nextTasksList, isCommit, appSms,uploads, filetype);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg=e.getMessage();
        }
        return "success";
    }
	
	private void initAppData(){
		String procinstId=ApplicationContextUtil.getContextObject("procinstId");
		appSms=appSmsService.getAppSmsDao().getByProcinstId(procinstId);
	    Person startPerson=appBusinessReqService.getAppBusinessReqDao().getPerson(Integer.valueOf(appSms.getApplyUser()));
	    Organization startDept=appBusinessReqService.getAppBusinessReqDao().getOrgByPerson(startPerson.getId());
	    appSms.setApplyUserName(startPerson.getName());
	    appSms.setApplyDeptName(startDept.getFullName());
	    
	    Person prodPerson=appBusinessReqService.getAppBusinessReqDao().getPerson(Integer.valueOf(appSms.getProdUser()));
	    Organization prodDept=appBusinessReqService.getAppBusinessReqDao().getOrgByPerson(prodPerson.getId());
	    appSms.setProdUserName(prodPerson.getName());
	    appSms.setProdDeptName(prodDept.getFullName());
	}
	
	public String showDetail(){
		String procInstId=ApplicationContextUtil.getContextObject("procinstId");
		initAppData();
        String toPage=ApplicationContextUtil.getContextObject("toPage");
        String flowTaskId=ApplicationContextUtil.getContextObject("flowTaskId");
        TaskView taskView=null;
        if("toSmsStart".equals(toPage)){
        	 Organization startDept=new Organization();
        	 startDept.setId(Integer.valueOf(appSms.getApplyDept()));
        	 taskView=appSmsService.getTaskService().getTaskView(flowTaskId,null,startDept);
        	 List<Person> prodList=appBusinessReqService.findProdListByRole();
             ApplicationContextUtil.getHttpServletRequest().setAttribute("prodList", prodList);
        }else{
        	taskView=appSmsService.getTaskService().getTaskView(flowTaskId);
        }
        ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", taskView);
        ApplicationContextUtil.getHttpServletRequest().setAttribute("appSms", appSms);
        // 取得已经上传文档
		List<ReqDocu> reqDocuList = appSmsService.getAppBusinessReqService().getAppBusinessReqDao().findDocuList(Integer.valueOf(procInstId));
		// 判断该步骤是否已上传文档start
		judgeDocuIsUpload(taskView, reqDocuList);
		setRepDocTableStyleList(reqDocuList);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("reqDocuList", reqDocuList);
        //转向阅办任务
        String taskType=taskView.getProcTranRecord().getTaskType();
        if("03".equalsIgnoreCase(taskType)){
        	String taskAppExt=taskView.getProcTranRecord().getTaskAppExt();
        	if(StringUtils.isNotBlank(taskAppExt)){
        		return taskAppExt;
        	}
        	return "toSmsForReDo";
        }
        if(StringUtils.isNotBlank(toPage)){
        	return toPage;
        }
		return "toSmsDetail";
	}
	
	/**
	 * 查年工单信息
	 * @return
	 */
	public String showInfo(){
		String procInstId=ApplicationContextUtil.getContextObject("procinstId");
		initAppData();
		//取得流程实例及任务信息
		
        ProcessInstView processInstView=appSmsService.getProcessPvcService().getProcessInstView(Integer.valueOf(procInstId));
        ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", processInstView);
        
        // 取得已经上传文档
		List<ReqDocu> reqDocuList = appSmsService.getAppBusinessReqService().getAppBusinessReqDao().findDocuList(Integer.valueOf(procInstId));
		setRepDocTableStyleList(reqDocuList);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("reqDocuList", reqDocuList);
		return "toSmsInfo";
		
	}
	/**
	 * 提交申请任务（业务数据修改）
	 * @return
	 */
	public String commitApplyTask(){
		String procinstId=ApplicationContextUtil.getContextObject("procinstId");
		String flowTaskId=ApplicationContextUtil.getContextObject("flowTaskId");
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);//保存
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String content=req.getParameter("commentComtent");
        setCommitTaskMsg(isCommit);
        appSms.setProcinstId(procinstId);
        //取得产品经理所在的部门
        Person prodPerson=new Person();
        prodPerson.setId(Integer.valueOf(appSms.getProdUser()));
        Organization prodDept=appBusinessReqService.getOrgByPerson(prodPerson);
        //
        if(prodDept!=null){
        	appSms.setProdDept(prodDept.getId().toString());
        }
        try {
        	setAllDateField(appSms);
        	AppSms appSmsDb=appSmsService.getAppSmsDao().getByProcinstId(appSms.getProcinstId());
        	Date opTime=appSmsDb.getOpTime();
        	Integer id=appSmsDb.getId();
        	BeanUtils.copyProperties(appSmsDb, appSms);
        	appSmsDb.setOpTime(opTime);
        	appSmsDb.setId(id);
			getAppSmsService().commitApplyTask(flowTaskId, content, nextTasksList, isCommit, appSmsDb,uploads, filetype,delDocumentIds);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
            returnMsg=e.getMessage();
		}
		return "success";
	}
	
	
	public String commitTask(){
		String flowTaskId=ApplicationContextUtil.getContextObject("flowTaskId");
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);//保存
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String content=req.getParameter("commentComtent");
        setCommitTaskMsg(isCommit);
		try {
			getAppSmsService().commitTask(flowTaskId, content, nextTasksList, isCommit, uploads, filetype, delDocumentIds);
		} catch (Exception e) {
			// TODO: handle exception
			returnMsg=e.getMessage();
		}
		return "success";
	}
	private void setAllDateField(AppSms appSms) throws ParseException{
		String sercodeDuetime=ApplicationContextUtil.getContextObject("appSms.sercodeDuetime");
		String idenfDuetime=ApplicationContextUtil.getContextObject("appSms.idenfDuetime");
		if(StringUtils.isNotBlank(sercodeDuetime)){
			appSms.setSercodeDuetime(DateUtil.parse(sercodeDuetime, "yyyy-MM-dd"));
		}
		if(StringUtils.isNotBlank(idenfDuetime)){
			appSms.setIdenfDuetime(DateUtil.parse(idenfDuetime, "yyyy-MM-dd"));
		}
	}
	
	public AppBusinessReqService getAppBusinessReqService() {
		return appBusinessReqService;
	}
	public void setAppBusinessReqService(AppBusinessReqService appBusinessReqService) {
		this.appBusinessReqService = appBusinessReqService;
	}
	public AppSmsService getAppSmsService() {
		return appSmsService;
	}
	public void setAppSmsService(AppSmsService appSmsService) {
		this.appSmsService = appSmsService;
	}
	public FlowTaskForm getFlowTaskForm() {
		return flowTaskForm;
	}
	public void setFlowTaskForm(FlowTaskForm flowTaskForm) {
		this.flowTaskForm = flowTaskForm;
	}

	public AppSms getAppSms() {
		return appSms;
	}

	public void setAppSms(AppSms appSms) {
		this.appSms = appSms;
	}

	public String getProcinstId() {
		return procinstId;
	}

	public void setProcinstId(String procinstId) {
		this.procinstId = procinstId;
	}
	
	public List<String> getFiletype() {
		return filetype;
	}

	public void setFiletype(List<String> filetype) {
		this.filetype = filetype;
	}

	public List<File> getUploads() {
		return uploads;
	}

	public void setUploads(List<File> uploads) {
		this.uploads = uploads;
	}
	
	public List<String> getDelDocumentIds() {
		return delDocumentIds;
	}

	public void setDelDocumentIds(List<String> delDocumentIds) {
		this.delDocumentIds = delDocumentIds;
	}
}
